<!-- 地址搜索 -->
<template>
  <div>
    <input type="text" @input="handleKeywork" />
    <ul>
      <li @click="goBackHome(item)" v-for="item in searchList" :key="item.id">
        {{item.name}} 地址：{{item.address}}
      </li>
    </ul>
    <div id="map-container"></div>
  </div>
</template>

<script>
export default {
  name: 'AddresSearch',
  data() {
    return {
      city: '',
      searchList:[]
    }
  },

  components: {},

  computed: {},

  created() {
    // console.log('this.$route.meta=>',this.$route.meta);

  },

  mounted() {
    var map = new AMap.Map('map-container', {
      resizeEnable: true,
      zoom:16
    })
    let address = this.$store.state.address
    if (address.name) {
        var marker = new AMap.Marker({
            position:[address.location.lng, address.location.lat]//位置
        })
        map.add(marker);//添加到地图
        map.setCenter([address.location.lng, address.location.lat],true,)
    }
    var _this = this
    AMap.plugin('AMap.CitySearch', function () {
      var citySearch = new AMap.CitySearch()
      citySearch.getLocalCity(function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // 查询成功，result即为当前所在城市信息
          console.log('result=>', result)
          console.log('this=>', this)
          _this.city = result.city
        }
      })
    })
  },

  methods: {
    handleKeywork(e) {
      let _this = this
      AMap.plugin('AMap.AutoComplete', function () {
        var autoOptions = {
          //city 限定城市，默认全国
          city:  _this.city
        }
        // 实例化AutoComplete
        var autoComplete = new AMap.AutoComplete(autoOptions)
        // 根据关键字进行搜索
        autoComplete.search(e.target.value, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(result)
          _this.searchList = result.tips
        })
      })
    },
    // 跳转到首页
    goBackHome(item){
      // 把数据存储到vuex
      this.$store.commit('updateAddress',item)
      // 跳转到首页
      this.$router.push({name:'home'})
    }
  }
}
</script>
<style lang='scss' scoped>
#map-container {
  width: 100%;
  height: 300px;
}
</style>